import Vue from 'vue'
import VueRouter from 'vue-router'
//  导入子组件
import login from '../views/login'
import home from '../views/home'
import question from '../views/question'
import movie from '../views/movie'
import my from '../views/my'
import notfound from '../views/notfound'
import edit from '../views/edit'
import article from '../views/article'
import search from '../views/search'
import result from '../views/result'
// 导入工具函数
import { getToken, removeToken } from '../utils/token'
import { Toast } from 'vant'
// 导入api
import { getUserInfo } from '../api/my'
// 导入仓库对象
import store from '../store'
Vue.use(Toast)
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/home',
    name: 'home',
    component: home,
    meta: {
      showTab: true
    }
  },
  {
    path: '/question',
    name: 'question',
    component: question,
    meta: {
      showTab: true
    }
  },
  {
    path: '/movie',
    name: 'movie',
    component: movie,
    meta: {
      showTab: true
    }
  },
  {
    path: '/my',
    name: 'my',
    component: my,
    meta: {
      showTab: true,
      needLogin: true // token没有正确不可访问？
    }
  },
  {
    path: '/notfound',
    name: 'notfound',
    component: notfound
  },
  {
    path: '/',
    redirect: home
  },
  {
    path: '*',
    redirect: notfound
  },
  {
    path: '/edit',
    name: 'edit',
    component: edit,
    meta: {
      needLogin: true // token没有正确不可访问？
    }
  },
  {
    path: '/article/:id',
    name: 'article',
    component: article
  },
  {
    path: '/search',
    name: 'search',
    component: search
  },
  {
    path: '/result',
    name: 'result',
    component: result
  }
]
// 吞掉 没有处理的 promise的错误
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 执行之后 阻断后续代码
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}
const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  // console.log(to.path)
  if (to.meta.needLogin !== true) {
    return next()
  }
  const tokenObj = getToken()
  if (tokenObj === null) {
    Toast.fail('请先登录')
    return next({ path: '/login', query: { back: to.path } })
  }
  // token不为空，本地的vuex中有用户信息
  if (store.state.userInfo.name) {
    // 用户信息存在
    return next()
  }
  getUserInfo()
    .then(res => {
      // console.log('res', res)
      store.commit('setUserInfo', res.data.data)
      next()
    })
    .catch(err => {
      // console.dir(err)
      if (err.response.status === 401) {
        removeToken()
        Toast.fail('请先登录')
        return next({ path: '/login', query: { back: to.path } })
      }
    })
  next()
})
export default router
